package com.lancoo.znbkxx.uis;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;


import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.adapter.MyNoteDeleteAdapter;
import com.lancoo.znbkxx.base.AppApplication;
import com.lancoo.znbkxx.base.BaseActivity;
import com.lancoo.znbkxx.beans.MyNoteItemBean;
import com.lancoo.znbkxx.beans.MyNoteList;
import com.lancoo.znbkxx.net.MyNoteApi;
import com.lancoo.znbkxx.net.OnSuccessAndFaultListener;
import com.lancoo.znbkxx.net.OnSuccessAndFaultSub;
import com.lancoo.znbkxx.views.SlideRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by TangJun on 2019/2/16
 */
public class MyNoteActivity extends BaseActivity implements View.OnClickListener{

    private ImageView ivBack;
    //private RecyclerView rvMyNote;
    private SlideRecyclerView rvMyNote;
    private TextView tvTitle;
    private List<MyNoteItemBean> noteList;
    // private MyNoteItemAdapter adapter;
    private MyNoteDeleteAdapter adapter;
    private EditText editText;
    private String titleName;
    private List<MyNoteItemBean> mSearchList;
    private long mLastSearchTime;
    private ImageView imageView;

    public static Intent getInstance() {
        Intent intent = new Intent(AppApplication.getInstance(), MyNoteActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.color_2884EC));
        findViews();
        getDate();
    }
    private void getDate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Gson gson = new Gson();
                        final MyNoteList infoBean = gson.fromJson(result,MyNoteList.class);
                        //{"TotalCount":6,"ModelNoteList":[{"NoteID":"PN_20190213d3559862-84a3-48ea-8024-ec7fce230dc4","QuesID":"CBBE09085DHE100009s","Title":"卷4第1题","TypeNo":"E","TypeName":"听力选择","GenreID":"1","GenreName":"听单句","Content":"在我心中一直都是那个样子、在","ImagePath":"/pictures/201902139579dc79-c034-4936-8575-35c87df0312f.jpeg|/pictures/20190213ae8ddaf7-28fa-477d-8218-d719f6e31116.jpeg|/pictures/20190221c8643e69-5006-449b-be07-3161a525e618.jpeg","UpdateTime":"2019-02-21 11:54:20.000"}]}
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        msg.what = 1;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj",errorMsg);
                    }
                };
                MyNoteApi.getMyNoteInfo(new OnSuccessAndFaultSub(l));


            }
        }).start();
    }

    private void findViews() {
        ivBack  = findViewById(R.id.iv_back);
        rvMyNote = findViewById(R.id.rv_my_note);
        tvTitle = findViewById(R.id.tv_title);
        editText = findViewById(R.id.et_Search);
        imageView = findViewById(R.id.iv_nodate);
        rvMyNote.setLayoutManager(new LinearLayoutManager(this));
        ivBack.setOnClickListener(this);
        editText.setOnEditorActionListener(new EditEditorActionListener());
        editText.addTextChangedListener(new EditTextChangeListener());
    }
    protected class EditEditorActionListener implements TextView.OnEditorActionListener {

        @Override
        public boolean onEditorAction(TextView textView, int actionId,
                                      KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchPaperByKeyword();
                tvTitle.setText("搜索结果");
            }
            return true;
        }
    }
    private void searchPaperByKeyword() {
        mSearchList = new ArrayList<>();
        String trim = editText.getText().toString().trim();
        if (System.currentTimeMillis() - mLastSearchTime > 1000) {
            mLastSearchTime = System.currentTimeMillis();
        } else {
            return;
        }
        if (!TextUtils.isEmpty(trim)) {
            searchPaperData(trim);
        }
        hideSoftKeyboard(this);
    }
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    private void searchPaperData(String keyString) {
        mSearchList.clear();
        adapter.setKeyString(keyString);
        for (int i = 0; i < noteList.size(); i++) {
            if (null != noteList.get(i).getContent() && noteList.get(i)
                    .getContent().toLowerCase().contains(keyString.toLowerCase())) {
                mSearchList.add(noteList.get(i));
            }
        }
        //dismissProcessDialog();
        if (mSearchList.size() > 0) {
            rvMyNote.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
            adapter.updateData(mSearchList);
        } else {
            rvMyNote.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
        }
    }
    private class EditTextChangeListener implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            String s1 = s + "";
            if (s1.length() > 0) {

            } else {
                rvMyNote.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                adapter.updateData(noteList);
                tvTitle.setText(titleName);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {

            if (TextUtils.isEmpty(arg0.toString())) {

            } else {

            }
        }
    }
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    noteList = new ArrayList<>();
                    MyNoteList myNoteList = (MyNoteList)msg.obj;
                    tvTitle.setText("我的笔记(" + myNoteList.getTotalCount() + ")");
                    titleName = "我的笔记(" + myNoteList.getTotalCount() + ")";
                    for (int i = 0; i < myNoteList.getModelNoteList().size(); i++){
                        MyNoteItemBean myNoteItemBean = new MyNoteItemBean();
                        myNoteItemBean.setContent(myNoteList.getModelNoteList().get(i).getContent());
                        myNoteItemBean.setQuesID(myNoteList.getModelNoteList().get(i).getQuesID());
                        myNoteItemBean.setNoteID(myNoteList.getModelNoteList().get(i).getNoteID());
                        myNoteItemBean.setTitle(myNoteList.getModelNoteList().get(i).getTitle());
                        myNoteItemBean.setImagePath(myNoteList.getModelNoteList().get(i).getImagePath());
                        myNoteItemBean.setUpdateTime(myNoteList.getModelNoteList().get(i).getUpdateTime());
                        noteList.add(myNoteItemBean);
                    }
                                      /*  adapter = new MyNoteItemAdapter(noteList);
                                        rvMyNote.setAdapter(adapter);
                                        adapter.setOnItemClickListener(new MyNoteItemAdapter.OnItemClickListener() {
                                                @Override
                                                public void onItemClick(View view, int position) {
                                                        getApplication().startActivity(MyNoteEditActivity.getInstance(noteList.get(position).getContent()));
                                                }
                                                @Override
                                                public void onItemLongClick(View view, int position) {

                                                }
                                        });*/
                    adapter = new MyNoteDeleteAdapter(noteList);
                    rvMyNote.setAdapter(adapter);
                    adapter.setOnDeleteClickListener(new MyNoteDeleteAdapter.OnDeleteClickLister() {
                        @Override
                        public void onDeleteClick(View view, int position) {
                            adapter.deleteItem(position);
                        }
                    });
                    adapter.setOnItemClickListener(new MyNoteDeleteAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            getApplication().startActivity(MyNoteEditActivity.getInstance(noteList.get(position).getContent(),noteList.get(position).getTitle(),noteList.get(position).getImagePath()));
                        }
                        @Override
                        public void onItemLongClick(View view, int position) {

                        }
                    });
                    break;
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
